#include <string>
#include <string.h>

#include "sqlite3/sqlite3.h"

#include "Mzhttpd.h"
#include "mzroute.h"

#include "utils/MzMd5.h"
#include "utils/MzTime.h"
#include "utils/MzSQL.h"
#include "utils/MzUrl.h"

char* Index(mz_http_headers* headers){
	std::string s = "hahaha";
	char* name = get_args_value(&headers->args, "name");
	if (name == NULL){
		name = "(no need of SaoMiaoQi and do not pwn, this is web)whoami, try ?name=";
		s = s+" "+name;
		//return
		char* ret = (char*)malloc(s.size()+1);
		strcpy(ret, s.c_str());
		return ret;
	}

	mzUrlDecode(name);
	std::string _name = name;
	s = s+" "+name;
	
	// simple waf
	int _tmp = _name.find(" ");
	//printf("> find: %d \n", _tmp);
	if (_tmp != -1){
		// hacker
		printf("> hacker!");
		//return
		char* ret = (char*)malloc(s.size()+1);
		strcpy(ret, s.c_str());
		return ret;
	}
	_tmp = _name.find("/**/");
	if (_tmp != -1){
		// hacker
		printf("> hacker!");
		//return
		char* ret = (char*)malloc(s.size()+1);
		strcpy(ret, s.c_str());
		return ret;
	}
	
	
	//std::string _sql = "select uname from user where uname=@uname;";
	std::string _sql = "select uname from user where uname='";
	_sql += name;
	_sql += "';";
	// sample for use mzsql
	MzSQL* mzsql = new MzSQL("./db/test.db");     // open db
	mzsql->prepareSql((char*)_sql.c_str());
	//mzsql->bindText("@uname", name);
	while (mzsql->step() == SQLITE_ROW){
		printf("result: [%s] \n", mzsql->columnText(0));
		s += "\r\n <br> oh! I known you!";
	}
	delete mzsql;
	
	//return
	char* ret = (char*)malloc(s.size()+1);
	strcpy(ret, s.c_str());
	return ret;
}



int main(){
	Mzhttpd* mzhttpd = new Mzhttpd(2333);
	
	add_route("/", (long)&Index);

	
	// start server
	mzhttpd->run();
	delete mzhttpd;
	return 0;
}
